#include "unp.h"
#include <sys/select.h>

void str_cli(FILE *fp, int fd)
{
    char readline[MAXLINE], recvline[MAXLINE];
    fd_set fdset;
    int max_fd;

    for ( ; ; ) {
        FD_ZERO(&fdset);
        FD_SET(fd, &fdset);
        FD_SET(fileno(fp), &fdset);
        max_fd = max(fd, fileno(fp)) + 1;
        select(max_fd, &fdset, NULL, NULL, NULL);
        
        if (FD_ISSET(fd, &fdset)) {
            if (Readline(fd, recvline, sizeof(recvline)) == 0) {
                err_quit("str_cli: server terminated");
            }
            Fputs(recvline, stdout);
        }

        if (FD_ISSET(fileno(fp), &fdset)) {
            if (Fgets(readline, sizeof(readline), fp) == NULL) {
                return;
            }
            Writen(fd, readline, strlen(readline));
        }
    }
}
